#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
全面清理系统 v2.0
专为重装系统后的持久化测试清理设计
确保系统完全恢复到初始状态，支持智能检测和安全清理
"""

import os
import sys
import json
import time
import subprocess
import shutil
import signal
import logging
import hashlib
import psutil
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Tuple, Optional, Any

class ComprehensiveCleanupSystem:
    """全面清理系统"""
    
    def __init__(self):
        self.version = "2.0.0"
        self.session_id = datetime.now().strftime("%Y%m%d_%H%M%S")
        self.start_time = time.time()
        
        # 配置路径
        self.base_dir = Path("/tmp/persistence_cleanup")
        self.log_dir = self.base_dir / "logs"
        self.backup_dir = self.base_dir / "backups"
        self.report_dir = self.base_dir / "reports"
        
        # 创建目录
        for dir_path in [self.base_dir, self.log_dir, self.backup_dir, self.report_dir]:
            dir_path.mkdir(parents=True, exist_ok=True)
        
        # 配置日志
        self.setup_logging()
        
        # 清理配置
        self.cleanup_config = {
            'ssh_key': {
                'files_to_clean': [
                    '/root/.ssh/authorized_keys',
                    '/root/.ssh/id_rsa',
                    '/root/.ssh/id_rsa.pub'
                ],
                'backup_files': ['/root/.ssh/authorized_keys'],
                'processes_to_stop': [],
                'services_to_stop': [],
                'restore_commands': [
                    'systemctl restart ssh',
                    'systemctl restart sshd'
                ]
            },
            'systemd_service': {
                'files_to_clean': [
                    '/etc/systemd/system/persistence-test.service',
                    '/etc/systemd/system/multi-user.target.wants/persistence-test.service'
                ],
                'backup_files': [],
                'processes_to_stop': ['persistence-test'],
                'services_to_stop': ['persistence-test'],
                'restore_commands': [
                    'systemctl daemon-reload',
                    'systemctl reset-failed'
                ]
            },
            'crontab': {
                'files_to_clean': [
                    '/var/spool/cron/root',
                    '/etc/cron.d/persistence-test'
                ],
                'backup_files': ['/etc/crontab'],
                'processes_to_stop': [],
                'services_to_stop': [],
                'restore_commands': [
                    'systemctl restart cron',
                    'systemctl restart crond'
                ]
            },
            'env_variable': {
                'files_to_clean': [],
                'backup_files': ['/root/.bashrc', '/etc/environment'],
                'processes_to_stop': [],
                'services_to_stop': [],
                'restore_commands': []
            },
            'file_trigger': {
                'files_to_clean': [
                    '/tmp/test_trigger.txt',
                    '/tmp/file_monitor.sh'
                ],
                'backup_files': [],
                'processes_to_stop': ['inotifywait'],
                'services_to_stop': [],
                'restore_commands': []
            },
            'alias': {
                'files_to_clean': [],
                'backup_files': ['/root/.bashrc'],
                'processes_to_stop': [],
                'services_to_stop': [],
                'restore_commands': []
            }
        }
        
        # 通用清理项目
        self.general_cleanup = {
            'temp_files': [
                '/tmp/persistence_*',
                '/tmp/test_*',
                '/tmp/*_test*',
                '/tmp/backdoor_*'
            ],
            'log_files': [
                '/tmp/*.log',
                '/var/log/persistence_*',
                '/var/log/test_*'
            ],
            'processes_keywords': [
                'persistence',
                'backdoor',
                'test_',
                'inotifywait'
            ]
        }
        
        # 清理结果
        self.cleanup_results = {}
        self.cleanup_errors = []
        self.backup_info = {}
        
        self.logger.info(f"全面清理系统 v{self.version} 初始化完成")
        self.logger.info(f"会话ID: {self.session_id}")
    
    def setup_logging(self):
        """设置日志系统"""
        log_file = self.log_dir / f"cleanup_{self.session_id}.log"
        
        # 配置日志格式
        log_format = '%(asctime)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s'
        
        # 配置日志记录器
        logging.basicConfig(
            level=logging.INFO,
            format=log_format,
            handlers=[
                logging.FileHandler(log_file, encoding='utf-8'),
                logging.StreamHandler(sys.stdout)
            ]
        )
        
        self.logger = logging.getLogger(__name__)
        self.logger.info("清理系统日志初始化完成")
    
    def run_command(self, command: str, timeout: int = 30) -> Tuple[bool, str, str]:
        """执行系统命令"""
        try:
            self.logger.debug(f"执行命令: {command}")
            
            result = subprocess.run(
                command,
                shell=True,
                capture_output=True,
                text=True,
                timeout=timeout
            )
            
            success = result.returncode == 0
            stdout = result.stdout.strip()
            stderr = result.stderr.strip()
            
            if not success:
                self.logger.warning(f"命令执行失败: {command}")
                self.logger.warning(f"错误输出: {stderr}")
            
            return success, stdout, stderr
            
        except subprocess.TimeoutExpired:
            self.logger.error(f"命令执行超时: {command}")
            return False, "", "命令执行超时"
        except Exception as e:
            self.logger.error(f"命令执行异常: {command}, 错误: {str(e)}")
            return False, "", str(e)
    
    def backup_file(self, file_path: str) -> bool:
        """备份文件"""
        try:
            if not os.path.exists(file_path):
                self.logger.debug(f"文件不存在，无需备份: {file_path}")
                return True
            
            # 生成备份文件名
            backup_name = f"{os.path.basename(file_path)}.backup_{self.session_id}"
            backup_path = self.backup_dir / backup_name
            
            # 复制文件
            shutil.copy2(file_path, backup_path)
            
            # 记录备份信息
            self.backup_info[file_path] = {
                'backup_path': str(backup_path),
                'original_size': os.path.getsize(file_path),
                'backup_time': datetime.now().isoformat(),
                'checksum': self.calculate_file_checksum(file_path)
            }
            
            self.logger.info(f"文件备份成功: {file_path} -> {backup_path}")
            return True
            
        except Exception as e:
            self.logger.error(f"文件备份失败: {file_path}, 错误: {str(e)}")
            return False
    
    def calculate_file_checksum(self, file_path: str) -> str:
        """计算文件校验和"""
        try:
            with open(file_path, 'rb') as f:
                content = f.read()
                return hashlib.md5(content).hexdigest()
        except:
            return ""
    
    def restore_file(self, file_path: str) -> bool:
        """恢复文件"""
        try:
            backup_info = self.backup_info.get(file_path)
            if not backup_info:
                self.logger.warning(f"未找到备份信息: {file_path}")
                return False
            
            backup_path = backup_info['backup_path']
            if not os.path.exists(backup_path):
                self.logger.error(f"备份文件不存在: {backup_path}")
                return False
            
            # 恢复文件
            shutil.copy2(backup_path, file_path)
            
            # 验证恢复
            if os.path.exists(file_path):
                restored_checksum = self.calculate_file_checksum(file_path)
                original_checksum = backup_info.get('checksum', '')
                
                if restored_checksum == original_checksum:
                    self.logger.info(f"文件恢复成功: {file_path}")
                    return True
                else:
                    self.logger.warning(f"文件恢复后校验和不匹配: {file_path}")
                    return False
            else:
                self.logger.error(f"文件恢复失败: {file_path}")
                return False
                
        except Exception as e:
            self.logger.error(f"文件恢复失败: {file_path}, 错误: {str(e)}")
            return False
    
    def stop_processes(self, keywords: List[str]) -> Dict[str, Any]:
        """停止相关进程"""
        result = {
            'stopped_processes': [],
            'failed_processes': [],
            'total_stopped': 0
        }
        
        try:
            # 查找匹配的进程
            matching_processes = []
            
            for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
                try:
                    proc_info = proc.info
                    proc_name = proc_info['name'].lower()
                    proc_cmdline = ' '.join(proc_info['cmdline']).lower()
                    
                    for keyword in keywords:
                        if keyword.lower() in proc_name or keyword.lower() in proc_cmdline:
                            matching_processes.append({
                                'pid': proc_info['pid'],
                                'name': proc_info['name'],
                                'cmdline': proc_info['cmdline']
                            })
                            break
                            
                except (psutil.NoSuchProcess, psutil.AccessDenied):
                    continue
            
            # 停止匹配的进程
            for proc_info in matching_processes:
                try:
                    pid = proc_info['pid']
                    name = proc_info['name']
                    
                    # 尝试优雅停止
                    os.kill(pid, signal.SIGTERM)
                    time.sleep(2)
                    
                    # 检查进程是否还在运行
                    if psutil.pid_exists(pid):
                        # 强制停止
                        os.kill(pid, signal.SIGKILL)
                        time.sleep(1)
                    
                    if not psutil.pid_exists(pid):
                        result['stopped_processes'].append(proc_info)
                        result['total_stopped'] += 1
                        self.logger.info(f"进程停止成功: {name} (PID: {pid})")
                    else:
                        result['failed_processes'].append(proc_info)
                        self.logger.error(f"进程停止失败: {name} (PID: {pid})")
                        
                except Exception as e:
                    result['failed_processes'].append(proc_info)
                    self.logger.error(f"停止进程异常: {proc_info}, 错误: {str(e)}")
            
            self.logger.info(f"进程停止完成: 成功 {result['total_stopped']} 个")
            
        except Exception as e:
            self.logger.error(f"停止进程失败: 错误: {str(e)}")
        
        return result
    
    def stop_services(self, service_names: List[str]) -> Dict[str, Any]:
        """停止系统服务"""
        result = {
            'stopped_services': [],
            'failed_services': [],
            'total_stopped': 0
        }
        
        for service_name in service_names:
            try:
                # 检查服务是否存在
                success, stdout, _ = self.run_command(f"systemctl list-unit-files {service_name}.service")
                if not success or service_name not in stdout:
                    self.logger.debug(f"服务不存在: {service_name}")
                    continue
                
                # 停止服务
                success, stdout, stderr = self.run_command(f"systemctl stop {service_name}")
                if success:
                    # 禁用服务
                    self.run_command(f"systemctl disable {service_name}")
                    
                    result['stopped_services'].append(service_name)
                    result['total_stopped'] += 1
                    self.logger.info(f"服务停止成功: {service_name}")
                else:
                    result['failed_services'].append({
                        'name': service_name,
                        'error': stderr
                    })
                    self.logger.error(f"服务停止失败: {service_name}, 错误: {stderr}")
                    
            except Exception as e:
                result['failed_services'].append({
                    'name': service_name,
                    'error': str(e)
                })
                self.logger.error(f"停止服务异常: {service_name}, 错误: {str(e)}")
        
        return result
    
    def clean_files(self, file_patterns: List[str]) -> Dict[str, Any]:
        """清理文件"""
        result = {
            'cleaned_files': [],
            'failed_files': [],
            'total_cleaned': 0,
            'total_size_freed': 0
        }
        
        for pattern in file_patterns:
            try:
                # 使用glob查找匹配的文件
                success, stdout, _ = self.run_command(f"find {os.path.dirname(pattern) or '/'} -name '{os.path.basename(pattern)}' 2>/dev/null")
                
                if success and stdout:
                    files = stdout.strip().split('\n')
                    
                    for file_path in files:
                        if not file_path or not os.path.exists(file_path):
                            continue
                        
                        try:
                            # 获取文件大小
                            file_size = os.path.getsize(file_path)
                            
                            # 删除文件
                            if os.path.isfile(file_path):
                                os.remove(file_path)
                            elif os.path.isdir(file_path):
                                shutil.rmtree(file_path)
                            
                            result['cleaned_files'].append({
                                'path': file_path,
                                'size': file_size
                            })
                            result['total_cleaned'] += 1
                            result['total_size_freed'] += file_size
                            
                            self.logger.info(f"文件清理成功: {file_path}")
                            
                        except Exception as e:
                            result['failed_files'].append({
                                'path': file_path,
                                'error': str(e)
                            })
                            self.logger.error(f"文件清理失败: {file_path}, 错误: {str(e)}")
                            
            except Exception as e:
                self.logger.error(f"清理文件模式失败: {pattern}, 错误: {str(e)}")
        
        self.logger.info(f"文件清理完成: 清理 {result['total_cleaned']} 个文件，释放 {result['total_size_freed']} 字节")
        return result
    
    def clean_mechanism(self, mechanism: str) -> Dict[str, Any]:
        """清理单个持久化机制"""
        self.logger.info(f"开始清理机制: {mechanism}")
        
        config = self.cleanup_config.get(mechanism, {})
        result = {
            'mechanism': mechanism,
            'success': False,
            'backup_results': {},
            'process_results': {},
            'service_results': {},
            'file_results': {},
            'restore_results': {},
            'errors': []
        }
        
        try:
            # 1. 备份重要文件
            backup_files = config.get('backup_files', [])
            for file_path in backup_files:
                backup_success = self.backup_file(file_path)
                result['backup_results'][file_path] = backup_success
                if not backup_success:
                    result['errors'].append(f"备份失败: {file_path}")
            
            # 2. 停止相关进程
            processes_to_stop = config.get('processes_to_stop', [])
            if processes_to_stop:
                process_result = self.stop_processes(processes_to_stop)
                result['process_results'] = process_result
                if process_result['failed_processes']:
                    result['errors'].append(f"进程停止失败: {len(process_result['failed_processes'])} 个")
            
            # 3. 停止相关服务
            services_to_stop = config.get('services_to_stop', [])
            if services_to_stop:
                service_result = self.stop_services(services_to_stop)
                result['service_results'] = service_result
                if service_result['failed_services']:
                    result['errors'].append(f"服务停止失败: {len(service_result['failed_services'])} 个")
            
            # 4. 清理文件
            files_to_clean = config.get('files_to_clean', [])
            if files_to_clean:
                file_result = self.clean_files(files_to_clean)
                result['file_results'] = file_result
                if file_result['failed_files']:
                    result['errors'].append(f"文件清理失败: {len(file_result['failed_files'])} 个")
            
            # 5. 执行恢复命令
            restore_commands = config.get('restore_commands', [])
            restore_results = []
            for command in restore_commands:
                success, stdout, stderr = self.run_command(command)
                restore_results.append({
                    'command': command,
                    'success': success,
                    'output': stdout,
                    'error': stderr
                })
                if not success:
                    result['errors'].append(f"恢复命令失败: {command}")
            
            result['restore_results'] = restore_results
            
            # 6. 特殊处理
            if mechanism == 'env_variable':
                self.clean_environment_variables()
            elif mechanism == 'alias':
                self.clean_bash_aliases()
            elif mechanism == 'crontab':
                self.clean_crontab_entries()
            
            # 判断总体成功状态
            result['success'] = len(result['errors']) == 0
            
            self.logger.info(f"机制清理完成: {mechanism}, 状态: {'成功' if result['success'] else '失败'}")
            
        except Exception as e:
            result['errors'].append(f"清理过程异常: {str(e)}")
            self.logger.error(f"机制清理失败: {mechanism}, 错误: {str(e)}")
        
        return result
    
    def clean_environment_variables(self):
        """清理环境变量"""
        try:
            # 清理 .bashrc 中的测试相关环境变量
            bashrc_path = "/root/.bashrc"
            if os.path.exists(bashrc_path):
                with open(bashrc_path, 'r') as f:
                    lines = f.readlines()
                
                # 过滤掉测试相关的行
                filtered_lines = []
                for line in lines:
                    line_lower = line.lower()
                    if not any(keyword in line_lower for keyword in ['persistence', 'test', 'backdoor']):
                        filtered_lines.append(line)
                
                # 写回文件
                with open(bashrc_path, 'w') as f:
                    f.writelines(filtered_lines)
                
                self.logger.info("环境变量清理完成")
            
            # 清理 /etc/environment
            env_path = "/etc/environment"
            if os.path.exists(env_path):
                with open(env_path, 'r') as f:
                    lines = f.readlines()
                
                filtered_lines = []
                for line in lines:
                    line_lower = line.lower()
                    if not any(keyword in line_lower for keyword in ['persistence', 'test', 'backdoor']):
                        filtered_lines.append(line)
                
                with open(env_path, 'w') as f:
                    f.writelines(filtered_lines)
                
                self.logger.info("/etc/environment 清理完成")
                
        except Exception as e:
            self.logger.error(f"环境变量清理失败: {str(e)}")
    
    def clean_bash_aliases(self):
        """清理Bash别名"""
        try:
            bashrc_path = "/root/.bashrc"
            if os.path.exists(bashrc_path):
                with open(bashrc_path, 'r') as f:
                    lines = f.readlines()
                
                # 过滤掉测试相关的别名
                filtered_lines = []
                for line in lines:
                    line_lower = line.strip().lower()
                    if line_lower.startswith('alias') and any(keyword in line_lower for keyword in ['test', 'persistence', 'll']):
                        continue
                    filtered_lines.append(line)
                
                # 写回文件
                with open(bashrc_path, 'w') as f:
                    f.writelines(filtered_lines)
                
                self.logger.info("Bash别名清理完成")
                
        except Exception as e:
            self.logger.error(f"Bash别名清理失败: {str(e)}")
    
    def clean_crontab_entries(self):
        """清理Crontab条目"""
        try:
            # 清理用户crontab
            success, stdout, _ = self.run_command("crontab -l")
            if success and stdout:
                lines = stdout.split('\n')
                filtered_lines = []
                
                for line in lines:
                    line_lower = line.lower()
                    if not any(keyword in line_lower for keyword in ['persistence', 'test', 'backdoor']):
                        filtered_lines.append(line)
                
                # 写回crontab
                if filtered_lines != lines:
                    crontab_content = '\n'.join(filtered_lines)
                    with open('/tmp/clean_crontab', 'w') as f:
                        f.write(crontab_content)
                    
                    self.run_command("crontab /tmp/clean_crontab")
                    os.remove('/tmp/clean_crontab')
                    
                    self.logger.info("用户crontab清理完成")
            
            # 清理系统crontab
            system_crontab = "/etc/crontab"
            if os.path.exists(system_crontab):
                with open(system_crontab, 'r') as f:
                    lines = f.readlines()
                
                filtered_lines = []
                for line in lines:
                    line_lower = line.lower()
                    if not any(keyword in line_lower for keyword in ['persistence', 'test', 'backdoor']):
                        filtered_lines.append(line)
                
                if filtered_lines != lines:
                    with open(system_crontab, 'w') as f:
                        f.writelines(filtered_lines)
                    
                    self.logger.info("系统crontab清理完成")
                    
        except Exception as e:
            self.logger.error(f"Crontab清理失败: {str(e)}")
    
    def general_cleanup(self) -> Dict[str, Any]:
        """执行通用清理"""
        self.logger.info("开始执行通用清理")
        
        result = {
            'temp_files': {},
            'log_files': {},
            'processes': {},
            'success': False,
            'errors': []
        }
        
        try:
            # 清理临时文件
            temp_patterns = self.general_cleanup.get('temp_files', [])
            if temp_patterns:
                temp_result = self.clean_files(temp_patterns)
                result['temp_files'] = temp_result
                if temp_result['failed_files']:
                    result['errors'].append(f"临时文件清理失败: {len(temp_result['failed_files'])} 个")
            
            # 清理日志文件
            log_patterns = self.general_cleanup.get('log_files', [])
            if log_patterns:
                log_result = self.clean_files(log_patterns)
                result['log_files'] = log_result
                if log_result['failed_files']:
                    result['errors'].append(f"日志文件清理失败: {len(log_result['failed_files'])} 个")
            
            # 停止相关进程
            process_keywords = self.general_cleanup.get('processes_keywords', [])
            if process_keywords:
                process_result = self.stop_processes(process_keywords)
                result['processes'] = process_result
                if process_result['failed_processes']:
                    result['errors'].append(f"进程停止失败: {len(process_result['failed_processes'])} 个")
            
            result['success'] = len(result['errors']) == 0
            self.logger.info(f"通用清理完成: {'成功' if result['success'] else '失败'}")
            
        except Exception as e:
            result['errors'].append(f"通用清理异常: {str(e)}")
            self.logger.error(f"通用清理失败: {str(e)}")
        
        return result
    
    def cleanup_all_mechanisms(self) -> Dict[str, Any]:
        """清理所有持久化机制"""
        self.logger.info("开始清理所有持久化机制")
        
        start_time = time.time()
        results = {}
        
        # 清理各个机制
        for mechanism in self.cleanup_config.keys():
            mechanism_result = self.clean_mechanism(mechanism)
            results[mechanism] = mechanism_result
            self.cleanup_results[mechanism] = mechanism_result['success']
        
        # 执行通用清理
        general_result = self.general_cleanup()
        results['general'] = general_result
        
        end_time = time.time()
        
        # 计算统计信息
        successful_mechanisms = sum(1 for r in results.values() if r.get('success', False))
        total_mechanisms = len(results)
        
        summary = {
            'total_time': end_time - start_time,
            'total_mechanisms': total_mechanisms,
            'successful_mechanisms': successful_mechanisms,
            'failed_mechanisms': total_mechanisms - successful_mechanisms,
            'success_rate': successful_mechanisms / total_mechanisms if total_mechanisms > 0 else 0,
            'results': results
        }
        
        self.logger.info(f"所有机制清理完成，成功率: {summary['success_rate']:.1%}")
        
        return summary
    
    def verify_cleanup(self) -> Dict[str, Any]:
        """验证清理结果"""
        self.logger.info("开始验证清理结果")
        
        verification_result = {
            'mechanisms': {},
            'overall_clean': False,
            'remaining_issues': [],
            'verification_score': 0,
            'max_score': 0
        }
        
        try:
            for mechanism in self.cleanup_config.keys():
                mechanism_verification = {
                    'files_removed': True,
                    'processes_stopped': True,
                    'services_stopped': True,
                    'clean': False
                }
                
                config = self.cleanup_config[mechanism]
                
                # 检查文件是否已删除
                for file_path in config.get('files_to_clean', []):
                    if os.path.exists(file_path):
                        mechanism_verification['files_removed'] = False
                        verification_result['remaining_issues'].append(f"文件仍存在: {file_path}")
                
                # 检查进程是否已停止
                for process_name in config.get('processes_to_stop', []):
                    for proc in psutil.process_iter(['name', 'cmdline']):
                        try:
                            proc_info = proc.info
                            if process_name.lower() in proc_info['name'].lower() or \
                               any(process_name.lower() in arg.lower() for arg in proc_info['cmdline']):
                                mechanism_verification['processes_stopped'] = False
                                verification_result['remaining_issues'].append(f"进程仍在运行: {process_name}")
                                break
                        except (psutil.NoSuchProcess, psutil.AccessDenied):
                            continue
                
                # 检查服务是否已停止
                for service_name in config.get('services_to_stop', []):
                    success, stdout, _ = self.run_command(f"systemctl is-active {service_name}")
                    if success and stdout.strip() == 'active':
                        mechanism_verification['services_stopped'] = False
                        verification_result['remaining_issues'].append(f"服务仍在运行: {service_name}")
                
                # 计算机制清理状态
                mechanism_verification['clean'] = all([
                    mechanism_verification['files_removed'],
                    mechanism_verification['processes_stopped'],
                    mechanism_verification['services_stopped']
                ])
                
                verification_result['mechanisms'][mechanism] = mechanism_verification
                
                if mechanism_verification['clean']:
                    verification_result['verification_score'] += 1
                verification_result['max_score'] += 1
            
            # 计算总体清理状态
            verification_result['overall_clean'] = len(verification_result['remaining_issues']) == 0
            
            self.logger.info(f"清理验证完成: {verification_result['verification_score']}/{verification_result['max_score']}")
            
        except Exception as e:
            self.logger.error(f"清理验证失败: {str(e)}")
            verification_result['remaining_issues'].append(f"验证过程异常: {str(e)}")
        
        return verification_result
    
    def generate_cleanup_report(self) -> str:
        """生成清理报告"""
        self.logger.info("生成清理报告")
        
        report_file = self.report_dir / f"cleanup_report_{self.session_id}.md"
        
        try:
            with open(report_file, 'w', encoding='utf-8') as f:
                f.write(f"# 全面清理系统报告 v{self.version}\n\n")
                f.write(f"**会话ID**: {self.session_id}\n")
                f.write(f"**生成时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                f.write(f"**清理耗时**: {time.time() - self.start_time:.2f} 秒\n\n")
                
                # 清理摘要
                f.write("## 📊 清理摘要\n\n")
                successful_count = sum(1 for success in self.cleanup_results.values() if success)
                total_count = len(self.cleanup_results)
                success_rate = successful_count / total_count if total_count > 0 else 0
                
                f.write(f"- **清理机制数量**: {total_count}\n")
                f.write(f"- **成功清理数量**: {successful_count}\n")
                f.write(f"- **失败清理数量**: {total_count - successful_count}\n")
                f.write(f"- **清理成功率**: {success_rate:.1%}\n\n")
                
                # 详细结果
                f.write("## 🧹 详细清理结果\n\n")
                for mechanism, success in self.cleanup_results.items():
                    status_icon = "✅" if success else "❌"
                    f.write(f"### {status_icon} {mechanism.upper()}\n\n")
                    f.write(f"**状态**: {'成功' if success else '失败'}\n\n")
                
                # 备份信息
                if self.backup_info:
                    f.write("## 💾 备份信息\n\n")
                    for original_path, backup_data in self.backup_info.items():
                        f.write(f"- **原文件**: `{original_path}`\n")
                        f.write(f"  - 备份路径: `{backup_data['backup_path']}`\n")
                        f.write(f"  - 备份时间: {backup_data['backup_time']}\n")
                        f.write(f"  - 文件大小: {backup_data['original_size']} 字节\n")
                        f.write(f"  - 校验和: {backup_data['checksum']}\n\n")
                
                # 错误信息
                if self.cleanup_errors:
                    f.write("## ⚠️ 清理错误\n\n")
                    for error in self.cleanup_errors:
                        f.write(f"- {error}\n")
                    f.write("\n")
                
                # 恢复建议
                f.write("## 🔄 恢复建议\n\n")
                f.write("如需恢复系统到清理前状态，可以使用以下命令:\n\n")
                f.write("```bash\n")
                f.write(f"python3 {__file__} --restore\n")
                f.write("```\n\n")
                
                f.write("---\n")
                f.write(f"*报告由全面清理系统 v{self.version} 自动生成*\n")
            
            self.logger.info(f"清理报告已生成: {report_file}")
            return str(report_file)
            
        except Exception as e:
            self.logger.error(f"生成清理报告失败: {str(e)}")
            return ""
    
    def print_summary(self):
        """打印清理摘要"""
        print("\n" + "="*70)
        print(f"🧹 全面清理系统 v{self.version} - 清理摘要")
        print("="*70)
        
        successful_count = sum(1 for success in self.cleanup_results.values() if success)
        total_count = len(self.cleanup_results)
        success_rate = successful_count / total_count if total_count > 0 else 0
        
        print(f"📊 总体统计:")
        print(f"  清理机制: {total_count}")
        print(f"  成功清理: {successful_count}")
        print(f"  失败清理: {total_count - successful_count}")
        print(f"  成功率: {success_rate:.1%}")
        print(f"  清理耗时: {time.time() - self.start_time:.2f} 秒")
        
        print(f"\n📋 详细结果:")
        for mechanism, success in self.cleanup_results.items():
            status_icon = "✅" if success else "❌"
            print(f"  {status_icon} {mechanism}")
        
        if self.backup_info:
            print(f"\n💾 备份文件: {len(self.backup_info)} 个")
            for original_path, backup_data in self.backup_info.items():
                print(f"  {original_path} -> {backup_data['backup_path']}")
        
        print(f"\n📁 报告文件:")
        print(f"  清理报告: {self.report_dir / f'cleanup_report_{self.session_id}.md'}")
        print(f"  详细日志: {self.log_dir / f'cleanup_{self.session_id}.log'}")
        
        print("="*70)

def main():
    """主函数"""
    import argparse
    
    parser = argparse.ArgumentParser(description="全面清理系统 v2.0")
    parser.add_argument('--cleanup', action='store_true', help='执行完整清理')
    parser.add_argument('--mechanism', type=str, help='清理特定机制')
    parser.add_argument('--verify', action='store_true', help='验证清理结果')
    parser.add_argument('--restore', action='store_true', help='恢复备份文件')
    parser.add_argument('--force', action='store_true', help='强制清理（跳过确认）')
    parser.add_argument('--quiet', action='store_true', help='静默模式')
    
    args = parser.parse_args()
    
    # 创建清理系统实例
    cleaner = ComprehensiveCleanupSystem()
    
    try:
        if args.restore:
            # 恢复备份文件
            print("恢复功能尚未实现")
            sys.exit(1)
        
        elif args.mechanism:
            # 清理特定机制
            if not args.force:
                confirm = input(f"确认清理机制 '{args.mechanism}'? (y/N): ")
                if confirm.lower() != 'y':
                    print("清理已取消")
                    sys.exit(0)
            
            result = cleaner.clean_mechanism(args.mechanism)
            cleaner.cleanup_results[args.mechanism] = result['success']
            
            if not args.quiet:
                print(f"\n机制 '{args.mechanism}' 清理结果: {'成功' if result['success'] else '失败'}")
        
        elif args.cleanup:
            # 执行完整清理
            if not args.force:
                confirm = input("确认执行完整清理? 这将删除所有持久化机制! (y/N): ")
                if confirm.lower() != 'y':
                    print("清理已取消")
                    sys.exit(0)
            
            cleaner.cleanup_all_mechanisms()
        
        elif args.verify:
            # 验证清理结果
            verification_result = cleaner.verify_cleanup()
            
            if not args.quiet:
                print(f"\n清理验证结果: {'完全清理' if verification_result['overall_clean'] else '部分清理'}")
                print(f"验证得分: {verification_result['verification_score']}/{verification_result['max_score']}")
                
                if verification_result['remaining_issues']:
                    print("\n剩余问题:")
                    for issue in verification_result['remaining_issues']:
                        print(f"  - {issue}")
        
        else:
            parser.print_help()
            sys.exit(0)
        
        # 生成报告
        if not args.quiet:
            cleaner.print_summary()
        
        cleaner.generate_cleanup_report()
        
        # 返回适当的退出码
        if cleaner.cleanup_results:
            success_rate = sum(1 for success in cleaner.cleanup_results.values() if success) / len(cleaner.cleanup_results)
            if success_rate >= 0.8:
                sys.exit(0)  # 成功
            elif success_rate >= 0.5:
                sys.exit(1)  # 部分成功
            else:
                sys.exit(2)  # 失败
        else:
            sys.exit(0)
            
    except KeyboardInterrupt:
        cleaner.logger.warning("清理被用户中断")
        sys.exit(130)
    except Exception as e:
        cleaner.logger.error(f"清理过程发生异常: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    main()